package dw.datamining;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.BasicConfigurator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import de.preisrobot.entity.Tb_Manufacturer;
import de.preisrobot.persistence.dao.ManufacturerDao;
import dw.database.ConntectionFactory;
import dw.database.JdbcStatement;
import dw.database.ResultMapper;

public class UpdateHersteller {

	static ManufacturerDao dao;
	static Connection c;

	public static void main(String[] args) throws SQLException,
			ClassNotFoundException {

		BasicConfigurator.configure();
		ApplicationContext appContext = new ClassPathXmlApplicationContext(
				"classpath*:applicationContext.xml");

		appContext.getBeanDefinitionNames();
		dao = (ManufacturerDao) appContext.getBean("manufacturerDao");

		  c = ConntectionFactory.createConnection();

		updateArtikelMitHersteller(c);
		c.close();
	}

	private static void updateArtikelMitHersteller(Connection c) {

		final List<Tb_Manufacturer> hertsller = dao.getAll();
		JdbcStatement st = new JdbcStatement(c);

		st.executeQuery("select * from artikel where manufacturer_id = 0", new ResultMapper() {

			@Override
			public void mapResult(ResultSet res) {
				try {
					while (res.next()) {
						String artikellink = res.getString("artikellink");
						
						long id = res.getLong("id");
						System.out.println(artikellink);
						if(artikellink != null){
							int manID =containsHersteller(artikellink,hertsller);
							if(manID > 0)
								update(id,manID);
						}
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}

			}
		});

	}

	protected static void update(long id, int manID) {
		JdbcStatement t = new JdbcStatement(c);
		 t.executeUpdate("update artikel set manufacturer_id = "+manID+" where id="+id);
		
	}

	protected static int containsHersteller(String artikellink,
			List<Tb_Manufacturer> hertsller) {
		
		for (Tb_Manufacturer manufacturer : hertsller) {
			String name = manufacturer.getName();
			if(artikellink.contains(name))
					return (int) manufacturer.getManufacturer_id();
		}
		 
		return -1;
		
	}

	private static List<Tb_Manufacturer> getHersteller() {

		List<Tb_Manufacturer> all = dao.getAll();

		for (Tb_Manufacturer amazonGrabUrl : all) {
			System.out.println(amazonGrabUrl);
		}
		return null;
	}

}
